﻿using AutoMapper;
using B.S.AuthCenter.Api.Write.Application.Command.Roles;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;

namespace B.S.AuthCenter.Api.Write.Application.Handler.Roles
{
    public class AddRoleHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        IBaseRepository<RoleModel> roleRepo;
        IMapper mapper;

        public AddRoleHandler(IBaseRepository<RoleModel> roleRepo, IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res=new ApiResult<int>();
            var role = roleRepo.GetAll().Where(c => c.RoleName == request.RoleName && !c.IsDeleted).Count();
            if (role >0)
            {
                res.Msg = "角色名称不能重复";
                res.Code=ApiEnum.Fail;
                return Task.FromResult(res);
            }
            var model=mapper.Map<RoleModel>(request);
            model.Creator=request.Creator;
            model.CreatorDate=DateTime.Now;
            int a=roleRepo.Add(model).Result;
            if(a>0)
            {
                res.Msg = "角色名称信息添加成功";
                res.Code=ApiEnum.Success;
                res.Datas = a;
                return Task.FromResult(res);
            }
            else
            {
                res.Msg = "角色名称信息添加失败";
                res.Code = ApiEnum.Success;
                res.Datas = a;
                return Task.FromResult(res);
            }
        }
    }
}
